import {createReducer} from 'redux-act';
import u from 'updeep';
import {createAction2} from '../util';
import {bed, up, get, nullKey, dataKey} from '../util/bed';
import * as ajax from '../util/ajax';
import * as http from '../util/http';
const [
    load,
    create,
    modify
] = [
    'specialdepartment_load',
    'specialdepartment_create',
    'specialdepartment_modify'
].map(createAction2);

export const actions = {
    load: (q = {}) => bed(ajax.get(http.makeUrl(`/specialdepartment`, q)), load),
    create: (data) => bed(ajax.post(`/specialdepartment`, data), create, {data}),
    modify: (data) => bed(ajax.put(`/specialdepartment`, data), modify, {data})
};

export default createReducer({
    [load]: get,
    [create]: (state, payload, {data}) => {
        let result = up(state, payload, nullKey);
        const {data: Id} = payload;
        if (Id) {
            data.Id = Id;
            result = u({[dataKey]: (arr) => [].concat(arr || [], [data])}, result);
        }
        return result;
    },
    [modify]: (state, payload, {data, done}) => {
        let result = up(state, payload);
        if (done) {
            result = u({[dataKey]: u.map(d => (d.Id === data.Id ? data : d))}, result);
        }
        return result;
    }
}, {});
